import datetime
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from .models import BookInstance, Book, Author, Genre


class RenewBookForm(forms.Form):
    renewal_date = forms.DateField(
        help_text="Enter a date between now and 4 weeks (default 3).",
        initial=datetime.date.today() + datetime.timedelta(weeks=3),
        widget=forms.DateInput(attrs={'type': 'date', 'class': 'form-control'})
    )

    def clean_renewal_date(self):
        data = self.cleaned_data['renewal_date']

        # Check if a date is not in the past.
        if data < datetime.date.today():
            raise ValidationError(_('Invalid date - renewal in past'))

        # Check if a date is in the allowed range (+4 weeks from today).
        if data > datetime.date.today() + datetime.timedelta(weeks=4):
            raise ValidationError(_('Invalid date - renewal more than 4 weeks ahead'))

        # Remember to always return the cleaned data.
        return data


class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'author', 'summary', 'isbn', 'genre']
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'summary': forms.Textarea(attrs={'class': 'form-control', 'rows': 4}),
            'isbn': forms.TextInput(attrs={'class': 'form-control'}),
            'genre': forms.CheckboxSelectMultiple(),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['author'].widget.attrs.update({'class': 'form-control'})


class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
        widgets = {
            'first_name': forms.TextInput(attrs={'class': 'form-control'}),
            'last_name': forms.TextInput(attrs={'class': 'form-control'}),
            'date_of_birth': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'date_of_death': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
        }

    def clean_date_of_death(self):
        date_of_birth = self.cleaned_data.get('date_of_birth')
        date_of_death = self.cleaned_data.get('date_of_death')

        if date_of_death and date_of_birth:
            if date_of_death <= date_of_birth:
                raise ValidationError(_('Date of death must be after date of birth'))

        return date_of_death


class BookInstanceForm(forms.ModelForm):
    class Meta:
        model = BookInstance
        fields = ['book', 'imprint', 'status', 'due_back', 'borrower']
        widgets = {
            'book': forms.Select(attrs={'class': 'form-control'}),
            'imprint': forms.TextInput(attrs={'class': 'form-control'}),
            'status': forms.Select(attrs={'class': 'form-control'}),
            'due_back': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'borrower': forms.Select(attrs={'class': 'form-control'}),
        }
